<?php 
include("../header.inc");
require_once("../DataBase.inc");

$center_id = $_GET["center_id"];
$role = $_GET["role"];

$interview_id = null;
$date = null;
if (isset($_GET["interview_id"]))
	$interview_id = $_GET["interview_id"];
else {
	$date = $_GET["date"];
	$room = $_GET["room"];
}

$q = "SELECT * FROM interview WHERE ";
if ($interview_id <> null)
	$q .= "interview_id=".$interview_id;
else 
	$q .= "interview_date='".$date."' AND room='".mysql_escape_string($room)."'";
$interviews = DataBase::query($q);

if (isset($_POST["username"])) {
    if ($role == "interviewer") {
        foreach ($interviews as $int)
            DataBase::update("interview",array("interview_id"=>$int["interview_id"]),array("interviewer_username"=>$_POST["username"]));
	echo "<b>User ".$_POST["username"]." assigned to ".count($interviews)." interview(s)</b><br/><br/>";
    } else {
	$ins = array();
	foreach ($interviews as $int)
		array_push($ins, array("interview_id"=>$int["interview_id"],"observer_username"=>$_POST["username"]));
	DataBase::insert_multiples("interview_observer", $ins);
	echo "<b>User ".$_POST["username"]." assigned to ".DataBase::number_of_affected_rows()." interview(s)</b><br/><br/>";
    }
}

function compare_time($t1, $t2) {
	if (intval($t1[0]) < intval($t2[0])) return -1;
	if (intval($t1[0]) > intval($t2[0])) return 1;
	if (intval($t1[1]) < intval($t2[1])) return -1;
	if (intval($t1[1]) > intval($t2[1])) return 1;
	return 0;
}

$min_time = null;
$max_time = null;
foreach ($interviews as $int) {
	if ($date == null) $date = $int["interview_date"];
	$start = explode(":",$int["interview_start_time"]);
	$end = explode(":",$int["interview_end_time"]);
	if ($min_time == null || compare_time($min_time, $start) > 0) $min_time = $start;
	if ($max_time == null || compare_time($max_time, $end) < 0) $max_time = $end;
}

require_once("../staff/activities.inc");
$free_staff = get_free_staff($date, implode(":",$min_time), implode(":",$max_time), $role, "department_name");

echo "<form action='?center_id=".$center_id."&role=".$role;
if ($interview_id <> null) echo "&interview_id=".$interview_id;
else echo "&date=".$date."&room=".urlencode($room);
echo "' method='post'>";
echo "Assign a new ".$role." for ".count($interviews)." interview(s) on ".$date." from ".$min_time[0]."h".$min_time[1]." to ".$max_time[0]."h".$max_time[1].": ";
echo "<select name='username'>";
foreach ($free_staff as $staff) echo "<option value=\"".$staff["username"]."\">".$staff["department_name"].": ".$staff["first_name"]." ".$staff["last_name"]."</option>";
echo "</select>";
echo "<button type='submit'>Ok</button>";
echo "</form>";
echo "<br/>";
echo "<i>Note: all staff listed above are ".$role."s and are free during this time.</i>";

echo "<br/><br/><a href='center.php?center_id=".$center_id."'>Go back to the interview center</a>";

include("../footer.inc");
?>